<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager;

use app\admin\model\merchant\Store;
use app\common\model\Merchant;
use app\common\model\MerchantImage;
use app\common\model\StoreImage;
use app\common\model\StoreInfo;
use app\common\model\User;
use think\Db;
use think\Exception;

class StoreManager extends BaseManager
{
    /**
     * 根据经纬度及公里数获取附近的门店信息
     * @param User|null $user
     * @param float $lng
     * @param float $lat
     * @param $radius
     * @param int $page
     * @param int $step
     * @return array
     */
    public static function List(User $user=null,float $lng,float $lat,$radius=5, int $page=1,int $step=10):array
    {
        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        if ($page <= 0){
            $page = 1;
        }
        $level = 0;
        try {

            if ($user && $user->level){
                $level = $user->level;
            }

            //$distance = SquarePoint($lng,$lat,$radius);
            $distance = getDistance($lat,$lng,$radius);
            $storeModel = new Store();
            $start = ($page - 1) * $step;

            $count = $storeModel->alias('s')
                ->join('level l','l.vl_id = s.level','left')
                ->where('s.status',Store::STATUS_NORMAL)
                ->where(function ($query) use($level,$distance){
//                    if ($level){
//                        $query->where('s.level','<=',$level);
//                    }

                    /*if (!empty($distance['right_bottom']) && !empty($distance['left_bottom']) && !empty($distance['right_top']) ){
                        $query->where('lat','between',[$distance['right_bottom']['lat'],$distance['right_top']['lat']])
                            ->where('long','between',[$distance['left_bottom']['lng'],$distance['right_bottom']['lng']]);
                    }*/
                    if (!empty($distance['minLat']) && !empty($distance['maxLat']) && !empty($distance['minLng']) && !empty($distance['maxLng'])){
                        $query->where('s.lat','between',[$distance['minLat'],$distance['maxLat']])
                            ->where('s.long','between',[$distance['minLng'],$distance['maxLng']]);
                    }

                    return $query;
                })
                ->count();

            $storeInfo = $storeModel->alias('s')
                ->join('level l','l.vl_id = s.level','left')
                ->where('s.status',Store::STATUS_NORMAL)
                ->where(function ($query) use($level,$distance){
//                    if ($level){
//                        $query->where('s.level','<=',$level);
//                    }

                    if (!empty($distance['minLat']) && !empty($distance['maxLat']) && !empty($distance['minLng']) && !empty($distance['maxLng'])){
                        $query->where('s.lat','between',[$distance['minLat'],$distance['maxLat']])
                            ->where('s.long','between',[$distance['minLng'],$distance['maxLng']]);
                    }
                    /*if (!empty($distance['right_bottom']) && !empty($distance['left_bottom']) && !empty($distance['right_top']) ){
                        $query->where('lat','between',[$distance['right_bottom']['lat'],$distance['right_top']['lat']])
                            ->where('long','between',[$distance['left_bottom']['lng'],$distance['right_bottom']['lng']]);
                    }*/
                    return $query;
                })
                ->field('s.id,s.store_name,s.lat,s.`long`,s.address,s.background_image,s.icon,s.description,s.business_end_hours,s.business_start_hours,s.narrate,l.vip_icon,l.vip_name,(st_distance(point(s.`long`,s.lat),point('.$lng.','.$lat.'))*111195/1000 ) as juli')
                ->order('s.id desc')
                ->limit($start,$step)
                ->select();
            if ($storeInfo){
                foreach ($storeInfo as $k=>$v){
                    if ($v['background_image'] && strrpos($v['background_image'],'https') === false){
                        $storeInfo[$k]['background_image'] = cdnurl($v['background_image']);
                    }else{
                        config('app.api_domain').$v['background_image'];
                    }

                    if ($v['vip_icon'] && strrpos($v['vip_icon'],'https') === false){
                        $storeInfo[$k]['vip_icon'] = cdnurl($v['vip_icon']);
                    }else{
                        config('app.api_domain').$v['vip_icon'];
                    }

                    if ($v['icon'] && strrpos($v['icon'],'https') === false){
                        $storeInfo[$k]['icon'] = cdnurl($v['icon']);
                    }else{
                        config('app.api_domain').$v['icon'];
                    }
                }
            }
            $pageData = page($count,$step,$page);

            $return['list'] = $storeInfo;
            $return = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($return);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
            self::setData($return);
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    public static function ListByUser(User $user, int $page=1,int $step=10):array
    {
        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        if ($page <= 0){
            $page = 1;
        }
        try {

            $storeModel = new Store();
            $start = ($page - 1) * $step;
            $isSuperManger = 0;
            $userId = $user->id;
            if (StoreInfo::where('merchant_id',$user->merchant_id)->where('user_id',$userId)->where('store_id',0)->where('is_manager',StoreInfo::IS_MANAGER)->count()){
                $isSuperManger = 1;
            }
            if ($isSuperManger){
                $count = $storeModel
                    ->alias('s')
                    ->join('level l','s.level = l.vl_id','inner')
                    ->where('s.status',Store::STATUS_NORMAL)
                    ->where('s.merchant_id',$user->merchant_id)
                    ->count();

                $storeInfo = $storeModel
                    ->alias('s')
                    ->join('level l','s.level = l.vl_id','inner')
                    ->where('s.status',Store::STATUS_NORMAL)
                    ->where('s.merchant_id',$user->merchant_id)
                    ->order('s.id desc')
                    ->field('s.*,l.vip_icon,l.vip_name,l.vip_rule')
                    ->limit($start,$step)
                    ->select();
            }else{
                $count = $storeModel
                    ->alias('s')
                    ->join('level l','s.level = l.vl_id','inner')
                    ->join('merchant_store_info msi','msi.store_id=s.id','inner')
                    ->where('s.status',Store::STATUS_NORMAL)
                    ->where('s.merchant_id',$user->merchant_id)
                    ->where(function ($query) use($isSuperManger,$userId){
                        if (!$isSuperManger && $userId){
                            return $query->where('msi.user_id',$userId);
                        }
                    })
                    ->count();

                $storeInfo = $storeModel
                    ->alias('s')
                    ->join('level l','s.level = l.vl_id','inner')
                    ->join('merchant_store_info msi','msi.store_id=s.id','inner')
                    ->where('s.status',Store::STATUS_NORMAL)
                    ->where('s.merchant_id',$user->merchant_id)
                    ->where(function ($query) use($isSuperManger,$userId){
                        if (!$isSuperManger && $userId){
                            return $query->where('msi.user_id',$userId);
                        }
                    })
                    ->order('s.id desc')
                    ->field('s.*,l.vip_icon,l.vip_name,l.vip_rule')
                    ->limit($start,$step)
                    ->select();
            }
            if ($storeInfo){
                foreach ($storeInfo as $k=>&$v){
                    $imageInfo = StoreImage::where('store_id',$v->id)->select();
                    if ($imageInfo){
                        foreach ($imageInfo as $sk=>$sv){
                            if (strrpos($sv->url,'https') === false){
                                $imageInfo[$sk]->url = cdnurl($sv->url);
                            }
                        }
                        $v->banner_image = $imageInfo;
                    }else{
                        $v->banner_image = [];
                    }
                    if ($v['background_image'] && strrpos($v['background_image'],'https') === false){
                        $storeInfo[$k]['background_image'] = cdnurl($v['background_image']);
                    }else{
                        config('app.api_domain').$v['background_image'];
                    }

                    if ($v['business_licence'] && strrpos($v['business_licence'],'https') === false){
                        $storeInfo[$k]['business_licence'] = cdnurl($v['business_licence']);
                    }else{
                        config('app.api_domain').$v['business_licence'];
                    }

                    if ($v['icon'] && strrpos($v['icon'],'https') === false){
                        $storeInfo[$k]['icon'] = cdnurl($v['icon']);
                    }else{
                        config('app.api_domain').$v['icon'];
                    }
                    if ($v['vip_icon'] && strrpos($v['vip_icon'],'https') === false){
                        $storeInfo[$k]['vip_icon'] = cdnurl($v['vip_icon']);
                    }else{
                        config('app.api_domain').$v['vip_icon'];
                    }
                }
            }
            $pageData = page($count,$step,$page);

            $return['list'] = $storeInfo;
            $return = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($return);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
            self::setData($return);
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 获取商户信息
     * @param User $user
     * @return array
     */
    public static function merchantInfo(User $user)
    {
        try {
            $merchantInfo = Merchant::where('id',$user->merchant_id)->find();
            if (!$merchantInfo){
                throw new Exception('商户信息不存在');
            }
            $imageInfo = MerchantImage::where('merchant_id',$user->merchant_id)->select();
            $merchantInfo->banner_image = null;
            if ($imageInfo){
                foreach ($imageInfo as $k=>$v){
                    if (strrpos($v->url,'https') === false){
                        $imageInfo[$k]->url = cdnurl($v->url);
                    }
                }
                $merchantInfo->banner_image = $imageInfo;
            }else{
                $object = (object)[];
                $merchantInfo->banner_image = $object;
            }

            if ($merchantInfo->id_card_front_image && strrpos($merchantInfo->id_card_front_image,'https') === false){
                $merchantInfo->id_card_front_image = cdnurl($merchantInfo->id_card_front_image);
            }

            if ($merchantInfo->id_card_back_image && strrpos($merchantInfo->id_card_back_image,'https') === false){
                $merchantInfo->id_card_back_image = cdnurl($merchantInfo->id_card_back_image);
            }

            if ($merchantInfo->icon && strrpos($merchantInfo->icon,'https') === false){
                $merchantInfo->icon = cdnurl($merchantInfo->icon);
            }
            unset($merchantInfo->business_license_image);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($merchantInfo);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage().$exception->getLine());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 获取门店详情
     * @param $id
     * @param $lng
     * @param $lat
     * @return array
     */
    public static function detail($id,$lng,$lat)
    {
        $storeModel = new \app\common\model\Store();
        try {
            $detail = $storeModel->alias('s')
                ->join('level l','l.vl_id=s.level','inner')
                ->where('s.id',$id)
                ->field('s.id,s.store_name,s.assistant_rate,s.lat,s.`long`,s.address,s.invite_code,s.narrate,s.background_image,s.icon,s.description,s.business_end_hours,s.business_start_hours,l.vip_icon,l.vip_name,(st_distance(point(s.`long`,s.lat),point('.$lng.','.$lat.'))*111195/1000 ) as juli')
                ->find();

            if (!$detail){
                throw new Exception('当前门店不存在');
            }

            if ($detail['background_image'] && strrpos($detail['background_image'],'https') === false){
                $detail['background_image'] = cdnurl($detail['background_image']);
            }else{
                config('app.api_domain').$detail['background_image'];
            }

            if ($detail['icon'] && strrpos($detail['icon'],'https') === false){
                $detail['icon'] = cdnurl($detail['icon']);
            }else{
                config('app.api_domain').$detail['icon'];
            }
            if ($detail['vip_icon'] && strrpos($detail['vip_icon'],'https') === false){
                $detail['vip_icon'] = cdnurl($detail['vip_icon']);
            }else{
                config('app.api_domain').$detail['vip_icon'];
            }

            $imageInfo = StoreImage::where('store_id',$id)->select();
            if ($imageInfo){
                foreach ($imageInfo as $sk=>$sv){
                    if (strrpos($sv->url,'https') === false){
                        $imageInfo[$sk]->url = cdnurl($sv->url);
                    }
                }
                $detail['banner_image'] = $imageInfo;
            }else{
                $detail['banner_image'] = [];
            }
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($detail);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 商户入驻申请
     * @param $user
     * @param $data
     * @param $trans
     * @return array
     */
    public static function merchantJoinIn($user, $data,$trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {
            $merchantModel = new \app\common\model\Merchant();
            $data['user_id'] = $user->id;
            $merchantInfo = $merchantModel->where('user_id',$user->id)->find();

            if ($merchantInfo){
                if (isset($merchantInfo['status']) && $merchantInfo['status'] == Merchant::STATUS_WAIT){
                    throw new Exception('商户审核中，请耐心等待');
                }

                if (isset($merchantInfo['status']) && $merchantInfo['status'] == Merchant::STATUS_NORMAL){
                    throw new Exception('您已申请入驻商户，请勿重复申请');
                }

                if (isset($merchantInfo['status']) && $merchantInfo['status'] == Merchant::STATUS_UNAVAILABLE){
                    throw new Exception('商户申请已被禁止，无法再次申请');
                }
            }


            $bannerImage = $data['banner_image'];
            unset($data['banner_image']);
            if ($merchantInfo){
                $merchantInfo->status = Merchant::STATUS_WAIT;
                $merchantInfo->company_name = $data['company_name'];
                $merchantInfo->legal_person = $data['legal_person'];
                $merchantInfo->id_card = $data['id_card'];
                $merchantInfo->id_card_front_image = $data['id_card_front_image'];
                $merchantInfo->id_card_back_image = $data['id_card_back_image'];
                $merchantInfo->icon = $data['icon'];
                $merchantInfo->description = $data['description'];
                $merchantInfo->credit_code = $data['credit_code'];
                $merchantInfo->business_license_image = $data['business_license_image'];
                $merchantInfo->address = $data['address'];
                $merchantInfo->phone = $data['phone'];
                $merchantInfo->mobile = $data['mobile'];
                $merchantInfo->updatetime = time();
                $merchantInfo->save();
            }else{
                $data['status'] = Merchant::STATUS_WAIT;
                $data['createtime'] = time();
                $data['updatetime'] = time();
                $merchantInfo = $merchantModel->create($data);
            }

            if ($bannerImage){
                $imageModel = new MerchantImage();
                $imageModel->where('merchant_id',$merchantInfo->id)->delete();
                $bannerImages = explode(',',$bannerImage);
                foreach ($bannerImages as $k=>$v){
                    $imageModel->save(['merchant_id'=>$merchantInfo->id,'url'=>$v,'created_time'=>time()]);
                }

            }

            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage()];
    }

    public static function getMerchantApplyInfo($user):array
    {
        try {
            $merchantModel = new \app\common\model\Merchant();
            $merchantInfo = $merchantModel->where('user_id',$user->id)->find();
            $message = '您还未申请入驻商户';
            if (!$merchantInfo){
                $message = '您还未申请入驻商户';
            }
            if ($merchantInfo['status'] == Merchant::STATUS_WAIT){
                $message = '商户审核中，请耐心等待';
            }

            if ($merchantInfo['status'] == Merchant::STATUS_NORMAL){
                $message = '您已成功入驻商户';
            }

            if ($merchantInfo['status'] == Merchant::STATUS_UNAVAILABLE){
                $message = '商户申请已被禁止';
            }

            if ($merchantInfo['status'] == Merchant::STATUS_REJECT){
                $message = '商户申请已被拒绝';
            }
            $data = ['status'=>$merchantInfo['status'] ?? '-1','message'=>$message,'reason'=>$merchantInfo['reason'] ?? ''];
            /*$merchantInfo->id_card_front_image = cdnurl($merchantInfo->id_card_front_image);
            $merchantInfo->id_card_back_image = cdnurl($merchantInfo->id_card_back_image);
            $merchantInfo->icon = cdnurl($merchantInfo->icon);
            $merchantInfo->business_license_image = cdnurl($merchantInfo->business_license_image);*/
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($data);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    public static function setAssistantRate($user, $store_id, $rate,$trans=true)
    {
        if ($trans)
            Db::startTrans();
        try {
            $storeModel = new \app\common\model\Store();
            $store = $storeModel->where('id',$store_id)->find();
            if (!$store){
                throw new Exception('门店不存在');
            }

            $StoreInfoModel = new StoreInfo();
            $storeInfo = $StoreInfoModel->where('merchant_id', $user->merchant_id)->where('user_id',$user->id)->where('is_manager',StoreInfo::IS_MANAGER)->find();
            if (!$storeInfo){
                throw new Exception('您当前无操作权限');
            }

            if (!empty($storeInfo['store_id']) && $storeInfo['store_id'] != $store_id){
                if (!$StoreInfoModel->where('merchant_id',$user->merchant_id)->where('store_id',$store_id)->where('user_id',$user->id)->where('is_manager',StoreInfo::IS_MANAGER)->find()){
                    throw new Exception('您非当前门店管理人员，无操作权限');
                }
            }

            $store->assistant_rate = $rate;
            $store->save();
            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage()];
    }

}